import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || ''
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.user?.role === 1
  },
  actions: {
    setUser(user) {
      this.user = user
      if (user) {
        localStorage.setItem('user', JSON.stringify(user))
      } else {
        localStorage.removeItem('user')
      }
    },
    setToken(tokenStr) {
      this.token = tokenStr
      if (tokenStr) {
        localStorage.setItem('token', tokenStr)
      } else {
        localStorage.removeItem('token')
      }
    },
    logout() {
      this.setUser(null)
      this.setToken('')
    },
    // 初始化状态
    init() {
      const storedUser = localStorage.getItem('user')
      const storedToken = localStorage.getItem('token')
      if (storedUser) this.setUser(JSON.parse(storedUser))
      if (storedToken) this.setToken(storedToken)
    }
  }
}) 